package cn.afterturn.oneopen.filter;

import cn.afterturn.oneopen.model.ChargeModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 计费拦截器
 *
 * @author by jueyue on 19-3-24.
 */
@Component
public class ChargeFilter implements GlobalFilter, Ordered {

    @Autowired
    RedisTemplate redisTemplate;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        String token = exchange.getRequest().getHeaders().get("token").get(0);
        String path  = exchange.getRequest().getPath().pathWithinApplication().value();
        return chain.filter(exchange).then(
                Mono.fromRunnable(() -> {
                    redisTemplate.opsForList().leftPush("CHARGE:REQUEST", new ChargeModel(token, path, "00"));
                })
        );

    }

    @Override
    public int getOrder() {
        return 3;
    }

}
